import {inject, injectable} from '@theia/core/shared/inversify';
import {
    Command, CommandContribution, CommandRegistry,
    MenuContribution, MenuModelRegistry
} from "@theia/core";
import {
    CommonMenus,
    WebSocketConnectionProvider
} from '@theia/core/lib/browser';

import { ITestServer, SERVER_PATH, ResBody } from '../common/test-control';

const CppSyncCommand: Command = {
    id: "CppSync:Command",
    label: "C++异步执行"
};
const NodeSyncCommand: Command = {
    id: "NodeSync:Command",
    label: "Node异步执行"
};

@injectable()
export class TestContribution implements CommandContribution, MenuContribution {
    testServer: ITestServer;
    constructor(
        @inject(WebSocketConnectionProvider) webSocketConnectionProvider: WebSocketConnectionProvider
    ) {
        this.testServer = webSocketConnectionProvider.createProxy(SERVER_PATH);
    }

    registerCommands(commands: CommandRegistry): void {

        commands.registerCommand(CppSyncCommand, {
            execute: () => {
                // 随机一个请求ID
                const reqId = Math.random() + '';
                this.testServer.cppDoLongTask(reqId).then((res: ResBody) => {
                    console.log(`%c CPP异步执行结束, 返回的数据是 ${ res.data }`, `font-size: ${34}px; color: red;`);
                    console.log(`%c 请求的ID: ${ reqId }, 返回的ID是 ${ res.resId } ID 匹配 = ${ reqId === res.resId }`, `font-size: ${34}px; color: red;`);

                });
            }
        });

        commands.registerCommand(NodeSyncCommand, {
            execute: () => {
                // 随机一个请求ID
                const reqId = Math.random() + '';
                this.testServer.nodeDoLongTask(reqId).then((res: ResBody) => {
                    console.log(`%c CPP异步执行结束, 返回的数据是 ${ res.data }`, `font-size: ${34}px; color: red;`);
                    console.log(`%c 请求的ID: ${ reqId }, 返回的ID是 ${ res.resId } ID 匹配 = ${ reqId === res.resId }`, `font-size: ${34}px; color: red;`);

                });
            }
        });
    }

    registerMenus(menus: MenuModelRegistry) {
        menus.registerMenuAction(CommonMenus.VIEW_VIEWS, { commandId: CppSyncCommand.id });
        menus.registerMenuAction(CommonMenus.VIEW_VIEWS, { commandId: NodeSyncCommand.id });
    }
}
